﻿from appium import webdriver
import time
import re
import itchat
import random
import os

# aapt dump badging
# 开启模拟点击权限 usb调试
# group_name_list是一个关于要发送信息的群的名字
# wechat_word_list是朋友圈关键字

# 保存微信号
weixin_num = ''
nick_name = ''
pengyouquan=''

def get_file_list(filename):
    with open(filename, 'r', encoding='utf-8-sig') as f:
        file_list = f.readlines()
    for i in range(len(file_list)):
        file_list[i] = file_list[i].rstrip('\n')
    return file_list


group_name_list = get_file_list('wechat_group')
wechat_word_list = get_file_list('wechat_word')

try:
    calNumber = get_file_list('calNumber.ini')[0]
    calNumber = int(calNumber[4:])
except:
    calNumber = 0


class WechatSpider(object):
    def __init__(self):
        port = random.randint(10000, 30000)
        print('正在启动服务中，请稍后')
        with open('start.bat', 'w') as f:
            f.write('appium -p {}'.format(port))
        os.system('start start.bat')
        time.sleep(5)
        phone_setting = {}
        phone_setting['platformName'] = 'Android'
        phone_setting['noReset'] = True
        phone_setting['deviceName'] = 'qipai_spider'
        phone_setting['appPackage'] = 'com.poker325.game'
        phone_setting['appActivity'] = 'org.cocos2dx.lua.AppActivity'
        self.driver = webdriver.Remote('http://127.0.0.1:{}/wd/hub'.format(port), phone_setting)
        print('连接成功')

    def enter(self):
        """
        进入朋友圈
        :return:
        """
        # 选项卡
        x = self.driver.get_window_size()['width']
        y = self.driver.get_window_size()['height']
        # print(x, y)
        s_x = 0.6 * x
        s_y = y - 10
        b_y = 0.4 * y
        time.sleep(8)
        self.driver.swipe(s_x, s_y, s_x, s_y, 1)
        self.driver.find_element_by_xpath('//*[@text="朋友圈"]').click()

    def crawl(self):
        content = self.driver.page_source
        self.driver.find_elements_by_xpath('//*[@content-desc="头像"]')[0].click()
        time.sleep(3)
        numcontent = self.driver.page_source

        self.driver.back()
        message = ''
        global weixin_num, nick_name
        weixin_num = ''
        nick_name = ''
        print(numcontent)


        weixin_num = ''.join(re.findall('"微信号:\s\s(\w+)"', numcontent))
        print(weixin_num)
        message += '微信号:' + weixin_num + '\n'
        first_content = re.findall('text="(.*?)"', content)
        while '' in first_content:
            first_content.remove('')

        # i是来判断误差的
        i = 0
        global pengyouquan
        try:
            if first_content[0] == '轻触更换主题照片':
                i = 1
            nick_name = first_content[1 + i]
            pengyouquan=first_content[2 + i]
            message += '朋友圈:' + first_content[2 + i] + '\n'
            message += '微信名:' + first_content[1 + i] + '\n'
            time.sleep(2)
        except Exception as e:
            print(e)
        self.driver.swipe(200, 700, 200, 1200)
        return message


class ItchatModel(object):
    def __init__(self):
        # ,enableCmdQR=True
        itchat.auto_login(hotReload=True)

    def get_send_ChatRoom(self, group_name_list, content):
        self.room_list = itchat.get_chatrooms(update=True)
        for group_name in group_name_list:
            iRoom = itchat.search_chatrooms(group_name)
            for room in iRoom:
                if room['NickName'] == group_name:
                    username = room['UserName']
                    itchat.send_msg(content, username)

                    mingpian_content = mingpian_content_get(weixin_num, nick_name)
                    itchat.send_raw_msg(42, mingpian_content, username)


def mingpian_content_get(weixinNum, nickname):
    mingpian_content = '<?xml version="1.0"?>\n<msg bigheadimgurl="" smallheadimgurl="" username="{}" nickname="{}"  shortpy="???????????" alias="{}" imagestatus="3" scene="17" province="" city="" sign="" sex="1" certflag="0" certinfo="" brandIconUrl="" brandHomeUrl="" brandSubscriptConfigUrl="" brandFlags="0" regionCode="AD" />\n'.format(
        weixinNum, nickname, weixinNum)
    return mingpian_content


com_wechat = ItchatModel()
wechat_p = WechatSpider()
time.sleep(4)

wechat_p.enter()
while 1:
    time.sleep(2)

    content = wechat_p.crawl()
    cache_content = re.sub('\\n', ' ', content)
    if cache_content in get_file_list('cache_word'):
        continue
    print(pengyouquan)
    for wechat_word in wechat_word_list:

        if wechat_word in pengyouquan:
            with open('cache_word', 'a+', encoding='utf-8') as f:
                f.write(cache_content + '\n')
            calNumber += 1
            content = '序号:' + str(calNumber) + '\n' + content
            com_wechat.get_send_ChatRoom(group_name_list, content)
            with open('calNumber.ini', 'w', encoding='utf-8') as f:
                f.write('NUM=' + str(calNumber))
